package com.storage.client;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.storage.FileStorageInfo;
import com.storage.configuration.StorageConfiguration;
import com.storage.exception.StorageException;
import lombok.Data;

import java.io.IOException;
import java.io.InputStream;
import java.util.function.Consumer;

import static com.storage.utils.LogUtils.printFileLog;

@Data
public class AliyunOssStorageClient implements StorageClient {

    private String client;

    private StorageConfiguration.AliyunOss aliyunOss;

    private String bucketName;

    public OSS init() {
        return new OSSClientBuilder().build(aliyunOss.getEndPoint(),aliyunOss.getAccessKey(),aliyunOss.getSecretKey());
    }

    public void shutdown(OSS oss) {
        if (oss != null){
            oss.shutdown();
        }
    }

    @Override
    public void upload(FileStorageInfo fileStorageInfo) {
        OSS oss=null;
        try {
            oss = init();
            ObjectMetadata objectMetadata=new ObjectMetadata();
            objectMetadata.setUserMetadata(fileStorageInfo.getUserMetadata());
            oss.putObject(bucketName,fileStorageInfo.getRelativePath(),fileStorageInfo.getInputStream(),objectMetadata);
        }catch (Exception e) {
            oss.deleteObject(bucketName,fileStorageInfo.getRelativePath());
            throw new StorageException("文件上传失败！"+printFileLog(fileStorageInfo),e);
        } finally {
            shutdown(oss);
        }

    }

    @Override
    public boolean exists(FileStorageInfo fileStorageInfo) {
        OSS oss = init();
        try {
            return oss.doesObjectExist(bucketName,fileStorageInfo.getRelativePath());
        } finally {
            shutdown(oss);
        }
    }


    @Override
    public boolean delete(FileStorageInfo fileStorageInfo) {
        OSS oss = init();
        try {
            if (fileStorageInfo.getRelativePath() != null) {
                oss.deleteObject(bucketName,fileStorageInfo.getRelativePath());
            }
            return true;
        } finally {
            shutdown(oss);
        }
    }

    @Override
    public void download(FileStorageInfo fileStorageInfo, Consumer<InputStream> consumer) {
        OSS oss = init();
        try {
            OSSObject object = oss.getObject(bucketName,fileStorageInfo.getRelativePath());
            try (InputStream in = object.getObjectContent()) {
                consumer.accept(in);
            } catch (IOException e) {
                throw new StorageException("文件下载失败！"+printFileLog(fileStorageInfo),e);
            }
        } finally {
            shutdown(oss);
        }
    }


}
